package com.zscat.mallplus.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.enums.ConstansValue;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItem;
import com.zscat.mallplus.oms.entity.OmsOrderReturnApply;
import com.zscat.mallplus.oms.service.IOmsOrderItemService;
import com.zscat.mallplus.oms.service.IOmsOrderReturnApplyService;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.sys.entity.SysUser;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单退货申请
 * </p>
 *
 * @author zscat
 * @since 2019-04-19
 */
@Slf4j
@RestController
@Api(tags = "OmsOrderReturnApplyController", description = "订单退货申请管理")
@RequestMapping("/oms/OmsOrderReturnApply")
public class OmsOrderReturnApplyController {
    @Resource
    private IOmsOrderReturnApplyService IOmsOrderReturnApplyService;
    @Resource
    private IUmsMemberService memberService;
    @Resource
    private IOmsOrderService orderService;
    @Resource
    private IOmsOrderItemService orderItemService;

    @SysLog(MODULE = "oms", REMARK = "根据条件查询所有订单退货申请列表")
    @ApiOperation("根据条件查询所有订单退货申请列表")
    @GetMapping(value = "list")
    @PreAuthorize("hasAuthority('oms:OmsOrderReturnApply:read')")
    public Object getOmsOrderReturnApplyByPage(OmsOrderReturnApply entity,
                                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<OmsOrderReturnApply> query = new QueryWrapper<>(entity).orderByDesc("create_time").groupBy("order_id").groupBy("id").select(ConstansValue.orderReturnApplyList_COLUMN);
            if (ValidatorUtils.notEmpty(entity.getCreateTime())) {
                query.between("create_time", dateFormat2.parse(dateFormat1.format(entity.getCreateTime()) + " 00:00:00"), dateFormat2.parse(dateFormat1.format(entity.getCreateTime()) + " 23:59:59"));
                entity.setCreateTime(null);
            }
            if (ValidatorUtils.notEmpty(entity.getHandleTime())) {
                query.between("handle_time", dateFormat2.parse(dateFormat1.format(entity.getHandleTime()) + " 00:00:00"), dateFormat2.parse(dateFormat1.format(entity.getHandleTime()) + " 23:59:59"));
                entity.setHandleTime(null);
            }
            return new CommonResult().success(IOmsOrderReturnApplyService.page(new Page<OmsOrderReturnApply>(pageNum, pageSize), query));
        } catch (Exception e) {
            log.error("根据条件查询所有订单退货申请列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "保存订单退货申请")
    @ApiOperation("保存订单退货申请")
    @PostMapping(value = "/create")
    public Object saveOmsOrderReturnApply(@RequestBody OmsOrderReturnApply entity) {
        try {
            if (IOmsOrderReturnApplyService.save(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("保存订单退货申请：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "oms", REMARK = "删除订单退货申请")
    @ApiOperation("删除订单退货申请")
    @GetMapping(value = "/delete/{id}")
    public Object deleteOmsOrderReturnApply(@ApiParam("订单退货申请id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("订单退货申请id");
            }
            if (IOmsOrderReturnApplyService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("删除订单退货申请：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "oms", REMARK = "给订单退货申请分配订单退货申请")
    @ApiOperation("查询订单退货申请明细")
    @GetMapping(value = "/{id}")
    @PreAuthorize("hasAuthority('oms:OmsOrderReturnApply:read')")
    public Object getOmsOrderReturnApplyById(@ApiParam("售后申请ID") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().failed("售后申请ID不能为空");
            }
            OmsOrderReturnApply orderReturnApply = IOmsOrderReturnApplyService.getById(id);
            // 根据订单ID查询订单商品清单
            List<OmsOrderItem> orderItemList = orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", orderReturnApply.getOrderId()));
            orderReturnApply.setOrderItemList(orderItemList);
            return new CommonResult().success(orderReturnApply);
        } catch (Exception e) {
            log.error("查询订单退货申请明细：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
    }

    @ApiOperation(value = "批量删除订单退货申请")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @ResponseBody
    @SysLog(MODULE = "pms", REMARK = "批量删除订单退货申请")
    @PreAuthorize("hasAuthority('oms:OmsOrderReturnApply:delete')")
    public Object deleteBatch(@RequestParam("ids") List<Long> ids) {
        boolean count = IOmsOrderReturnApplyService.removeByIds(ids);
        if (count) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "oms", REMARK = "售后审核")
    @ApiOperation("售后审核")
    @RequestMapping(value = "/update/status", method = RequestMethod.POST)
    public Object updateStatus(@RequestBody OmsOrderReturnApply orderReturnApply) {
        // 获取当前登录用户
        SysUser user = UserUtils.getCurrentMember();
        if (null != user) {
            orderReturnApply.setHandleMan(user.getNickName());
            orderReturnApply.setHandleTime(new Date());
        }

        try {
//            if (orderReturnApply.getStatus() == 2) { // 审核通过
//                if (orderReturnApply.getType() == 1 || orderReturnApply.getType() == 2) { // 售后类型为退款
//                    // 根据订单ID查询订单详情
//                    OmsOrder order = orderService.getById(orderReturnApply.getOrderId());
//                    if (order.getPayType() == 3) { // 用户使用余额支付，审核后直接退回到用户余额
//                        // 根据售后申请ID查询售后详情
//                        BigDecimal returnAmount = IOmsOrderReturnApplyService.getById(orderReturnApply.getId()).getReturnAmount();
//                        // 根据会员ID查询会员详情
//                        UmsMember member = memberService.getById(orderReturnApply.getMemberId());
//                        // 退款到用户余额
//                        member.setBlance(member.getBlance().add(returnAmount));
//                        memberService.updateById(member);
//                    }
//                }
//            }

            boolean isTrue = IOmsOrderReturnApplyService.update(orderReturnApply, new QueryWrapper<OmsOrderReturnApply>().eq("order_id", orderReturnApply.getOrderId()));
            if (isTrue) {
                return new CommonResult().success("审核成功");
            } else {
                return new CommonResult().failed("审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed(e.getMessage());
        }
    }
}
